using System;
using System.Threading;

namespace Clandestine.Graphics
{
	public class RenderingNotBlockedException : Exception { }
	
	internal class RenderMutex
	{
		private Thread acquiredBy = null;
		private int recursiveAcquiredCount = 0;
		private Mutex mutex = new Mutex();
		
		public void BlockRendering()
		{
			mutex.WaitOne();
			lock (this)
			{
				if (acquiredBy == Thread.CurrentThread)
					recursiveAcquiredCount++;
				acquiredBy = Thread.CurrentThread;
			}
		}
		
		public void UnblockRendering()
		{
			lock (this)
			{
				if (recursiveAcquiredCount > 0)
					recursiveAcquiredCount--;
				else
					acquiredBy = null;
			}
			
			mutex.ReleaseMutex();
		}
		
		public bool HasMutex()
		{
			return this.HasMutex(Thread.CurrentThread);
		}
		
		public bool HasMutex(Thread t)
		{
			if (acquiredBy == t)
				return true;
			return false;
		}
	}
}

